from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django.utils.safestring import mark_safe

from tools.form.form import PrettynumForm, PrettyEditModelForm
from tools.utils.PageData import PageData
from tools.models import models
from django import forms

from tools.utils.modelform import BootStrapModelForm


# 靓号管理
def prettynum_list(request):
    """ 靓号管理 """
    # # 插入300条数据
    # for i in range(300):
    #     models.PrettyNum.objects.create(mobile='18188888888', price=10, level=1, status=1)

    data_dict = {}  # 创建一个空字典用于存储查询条件
    search_data = request.GET.get("q", "")  # 从URL的GET参数中获取搜索关键词，http://yourdomain.com/prettynum/?q=138
    if search_data:  # 如果搜索关键词存在
        data_dict["mobile__contains"] = search_data  # 构建查询条件

    # 1.根据用户想要访问的页码，计算出起止位置
    page = int(request.GET.get("page", 1))
    page_size = 10  # 每页显示10条数据
    start = (page - 1) * page_size
    end = page * page_size

    # 获取所有数据并按level降序排列
    # queryset = models.PrettyNum.objects.all().order_by("-level")
    querySet = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]

    # 数据总条数
    total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()

    # 总页码
    total_page_count, div = divmod(total_count, page_size)
    if div:
        total_page_count += 1

    # 计算出，显示当前页面的前5页、后5页
    plus = 5
    start_page = page - plus
    end_page = page + plus + 1

    # 页码
    page_str_list = []
    for i in range(start_page, end_page):
        if i == page:
            ele = '<li class="activate"><a herf="?page={}">{}</a></li>'.format(i, i)
        else:
            ele = '<li><a herf="?page={}">{}</a></li>'.format(i, i)
        page_str_list.append(ele)

    # 尾页
    page_str_list.append('<li><a herf="?page={}">尾页</a></li>'.format(total_page_count))

    page_string = mark_safe("".join(page_str_list))

    # querySet = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]
    return render(request, "testpretty/prettynum_list.html", {"querySet": querySet, "page_string": page_string})


def pretty_list(request):
    # pretty_list = models.PrettyNum.objects.all()
    """靓号列表"""

    print(request.GET)
    print(request.GET.urlencode())

    dict_data = {}
    # 如果是空字典,表示获取所有
    # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
    search_data = request.GET.get('query', "")
    if search_data:
        # 在表格中搜素包含输入框当中的数据, 这里搜素的是手机号, key为mobile__contains
        dict_data["mobile__contains"] = search_data

    # select * from 表 by level desc;
    # data_dict 如果是空字典,表示获取所有
    queryset = models.PrettyNum.objects.filter(**dict_data).order_by("-level")

    ### 引入封装的 PageData/Pagination 类并初始化
    # 初始化
    page_object = PageData(request, queryset, page_size=10, page_param="page")
    page_queryset = page_object.page_queryset

    # 调用对象的html方法,生成页码
    page_string = page_object.page_html()

    context = {
        "querySet": page_queryset,  # 分页的数据
        "search_data": search_data,  # 搜索的内容
        "page_string": page_string,  # 页码
    }

    return render(request, "testpretty/prettynum_list.html", context)

    # # pretty_list = models.PrettyNum.objects.all()
    # # 搜索信息
    # dict_data = {}
    # # 获取搜素框里的内容, 就是获取网址里面的search参数的值
    # value = request.GET.get('query', "")  # 不加后面的 "", 首次访问浏览器,搜索框中不会显示前端页面中的 placeholder="Search for..." 属性
    # if value:
    #     # 在表格中搜素包含输入框当中的数据, 这里搜素的是手机号, key为mobile__contains
    #     dict_data["mobile__contains"] = value
    # # select * from 表 by level desc;
    # # data_dict 如果是空字典,表示获取所有
    # pretty_list = models.PrettyNum.objects.filter(**dict_data).order_by("-level")
    # # 分页
    # page_object = PageData(request, pretty_list)
    # # 调用我们自己写的page_html函数, 在PageData类当中。
    # page_string = page_object.page_html()
    # # 不能忘记将page_string传给前端。加入search_data的目的是,当搜索后,搜索框内的值不会置为空
    # return render(request, "testpretty/prettynum_list.html",
    #               {"querySet": page_object.page_queryset, "page_string": page_string, "search_data": value})


# 新增靓号

def prettynum_add(request):
    """ 添加靓号 ModelForm版本 """
    if request.method == "GET":
        form = PrettynumForm()
        return render(request, "testpretty/prettynum_add.html", {"form": form})

    # 用post提交数据，数据校验
    form = PrettynumForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # {'name': '程青松', 'password': '789', 'age': 88, 'account': Decimal('88888'), 'gender': 1, 'testdepart': <Department: IT测试部>}
        print(form.cleaned_data)
        # models.UserInfo.objects.create(...)
        form.save()
        return redirect("/tools/pretty/list/")

    # 校验失败（在页面上显示错误信息）
    return render(request, "testpretty/prettynum_add.html", {"form": form})


def prettynum_edit(request, nid):
    """ 修改靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = PrettynumForm(instance=row_object)
        return render(request, "testpretty/prettynum_edit.html", {"form": form})

    form = PrettynumForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的数据，如果想在用户输入以外增加一些值
        # form.instance.字段名 = 值
        form.save()
        return redirect("/tools/pretty/list/")
    return render(request, "testpretty/prettynum_edit.html", {"form": form})


# 编辑靓号

def pretty_edit(request, nid):
    """编辑靓号"""
    row_obj = models.PrettyNum.objects.filter(id=nid).first()

    # GET请求
    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_obj)
        return render(request, "testpretty/prettynum_edit.html", {"form": form})

    # POST请求
    form = PrettyEditModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return redirect("/tools/pretty/list/")

    return render(request, "testpretty/prettynum_edit.html", {"form": form})


def prettynum_delete(request, nid):
    """ 删除靓号 """
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/tools/pretty/list/")





